#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import cx_Oracle, time

class DataBase():
    def __init__(self):
        # engine = create_engine("oracle+cx_oracle://<username>:<password>@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = <host>)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = devdb)))")
        self.database_url = 'oracle://tap:tap123@10.10.8.107:1521/crmdb'
        # self.database_url = "oracle+cx_oracle://tap:tap123@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.8.107)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = crmdb)))"
        self.getSession()


    def getSession(self):
        engine = create_engine(self.database_url, echo=False)
        Session = sessionmaker(bind=engine)
        self.session = Session()

    def close(self):
        self.session.close()

    def runSql(self,sql,param=None):
        try:
            if param is None:
                self.session.execute(sql)
            else:
                self.session.execute(sql=sql, params=param)
        except cx_Oracle.DatabaseError, e:
            time.sleep(10)
            self.runSql(sql, param=param)